import React, { forwardRef, useState, useImperativeHandle } from 'react';
import { Modal, Form, Select, Upload, Button, message } from 'antd';
import { Authorized } from '@/components';
import permission from '@/config/permission';
import enums from '@/enums';
import { useCloudRegionOptions, useDownloadOssImportTemplate, useCreateTask } from './hooks';

/**
 * 导入任务表单
 */
function CreateTaskForm(props) {
    const { form } = props;

    const acceptList = ['.csv', '.xls', '.xlsx', '.xlsm'];
    const acceptInfo = `支持的文件格式为 ${acceptList.join('、')}，每个 sheet 数据不超过 1000 条。`;

    const cloudRegionOptions = useCloudRegionOptions();
    const downloadOssImportTemplate = useDownloadOssImportTemplate({
        onSuccess() {
            message.success('下载成功');
        },
        onError() {
            message.error('下载失败');
        },
    });

    return (
        <Form form={form} noValidate autoComplete="off" labelCol={{ span: 6 }} wrapperCol={{ span: 14 }}>
            <Form.Item label="云区域名称" name="cloudRegionCode" rules={[{ required: true, message: '请选择' }]}>
                <Select
                    allowClear
                    showSearch
                    optionFilterProp="label"
                    loading={cloudRegionOptions.loading}
                    options={cloudRegionOptions.data}
                    placeholder="请选择"
                    onChange={(value) => {
                        form.setFieldValue(
                            'cloudRegionName',
                            cloudRegionOptions.data.find((option) => option.value === value)?.label
                        );
                    }}
                />
            </Form.Item>
            <Form.Item noStyle name="cloudRegionName">
                <></>
            </Form.Item>
            <Form.Item label="导入任务类型" name="ossFileUploadType" rules={[{ required: true, message: '请选择' }]}>
                <Select
                    allowClear
                    showSearch
                    optionFilterProp="label"
                    options={enums.ossImport.taskTypes.options()}
                    placeholder="请选择"
                />
            </Form.Item>
            <Authorized authority={permission.resourceImportTasks_downloadOssImportTemplate} noMatch={null}>
                <Form.Item label="模板下载">
                    <Button
                        style={{ padding: 0 }}
                        type="link"
                        loading={downloadOssImportTemplate.loading}
                        onClick={() => {
                            downloadOssImportTemplate.run();
                        }}
                    >
                        导入模板.xlsx
                    </Button>
                </Form.Item>
            </Authorized>
            <Form.Item
                label="上传文件"
                name="fileList"
                valuePropName="fileList"
                getValueFromEvent={(e) => e.fileList}
                rules={[{ required: true, message: '请选择' }]}
                extra={acceptInfo}
            >
                <Upload
                    accept={acceptList.join(',')}
                    maxCount={1}
                    beforeUpload={(file) => {
                        if (!acceptList.includes(file.name.match(/\.\w+$/)?.[0])) {
                            message.error(acceptInfo);
                            return Upload.LIST_IGNORE;
                        }
                    }}
                    customRequest={({ onSuccess }) => {
                        onSuccess();
                    }}
                >
                    <Button>上传文件</Button>
                </Upload>
            </Form.Item>
        </Form>
    );
}

/**
 * 导入任务模态框
 */
function CreateTaskModal(props, ref) {
    const { onSuccess } = props;

    const [visible, setVisible] = useState(false);
    const [form] = Form.useForm();
    const { resetFields, validateFields } = form;

    const createTask = useCreateTask({
        onSuccess() {
            setVisible(false);
            onSuccess();
            message.success('导入成功');
        },
        onError(err) {
            message.error(err.message);
        },
    });

    useImperativeHandle(ref, () => ({
        open() {
            resetFields();
            setVisible(true);
        },
    }));

    return (
        <Modal
            open={visible}
            title="导入"
            okButtonProps={{ loading: createTask.loading }}
            onOk={() => {
                validateFields().then(createTask.run);
            }}
            onCancel={() => {
                setVisible(false);
            }}
        >
            <CreateTaskForm form={form} />
        </Modal>
    );
}

export default forwardRef(CreateTaskModal);
